//
//  SinaAuthController.m
//  YuiKe
//
//  Created by yuike5 yuike5 on 11-10-25.
//  Copyright 2011年 yuike. All rights reserved.
//

#import "WeiboAuthController.h"
//#import "TencWeibo.h"
#import "SinaWeibo.h"
//#import "YuiKeMobile.h"
#import "mcf.h"
#import "QQShare.h"

@implementation WeiboAuthController
@synthesize authview;

+(WeiboAuthController*) present:(UIViewController*)selfz   weibo:(int)snsid
{
    WeiboAuthController* temp = [[WeiboAuthController alloc] initWithNibName:@"WeiboAuthController" bundle:nil weibo:snsid ];
    [temp autorelease];    
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:temp];
    [navi autorelease];    
    navi.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navi.modalPresentationStyle = UIModalPresentationFormSheet;
    [selfz presentModalViewController:navi animated:YES];
    return temp;
}


static BOOL g_setFollowWhenAuth = TRUE;
+(void) setFollowWhenAuth:(BOOL)dofollow {
    g_setFollowWhenAuth = dofollow;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil weibo:(int)weiboid
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        // 不能有缓存，否则 微博 授权会 存在问题。
        //NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
        //[NSURLCache setSharedURLCache:sharedCache];
        
        
        if (weiboid == SNS_ID_SINA_WEIBO) {
            weibo = [[SinaWeibo alloc] init];
        } 
        
        else if (weiboid == SNS_ID_QQ_SHARE) {
            weibo = [[QQShare alloc ] init];
        }
        
//        else if (weiboid == SNS_ID_TENC_WEIBO) {
//            weibo = [[TencWeibo alloc] init];
//        } 
//        else if (weiboid == SNS_ID_TAOBAO_OPEN) {
//            weibo = [[TaobaoOpen alloc] init];
//        } 
        else {
            assert(false);
        }
        // Custom initialization
        self.title = [weibo title];

        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (NSString* str in [weibo urlStringsforCookies]) {
            NSArray* theCookies = [storage cookiesForURL:[NSURL URLWithString: str]];
            for (NSHTTPCookie* cookie in theCookies) {
                [storage deleteCookie:cookie];
            }
        }
    }
    return self;
}

-(void) dealloc
{
    authview.delegate = nil;
	[authview loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @""]]];
    YRelease(authview)
    
    [weibo setDelegateNilAll];
    YRelease(weibo)
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
    DEF_didReceiveMemoryWarning;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    
    if ([authview respondsToSelector: @selector(setDetectsPhoneNumbers:)]) [(id) authview setDetectsPhoneNumbers: NO];
	if ([authview respondsToSelector: @selector(setDataDetectorTypes:)]) [(id) authview setDataDetectorTypes: 0];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    int count = self.navigationController.viewControllers.count;
    if (count == 1) { // 堆栈底的 controller
        self.navigationItem.rightBarButtonItem = 
        [[[UIBarButtonItem alloc] initWithTitle:@"返回"
                                          style:UIBarButtonItemStyleBordered
                                         target:self 
                                         action:@selector(doneItemPressed:)] autorelease];
        isNavigationControllerModel = false;
    } else {
        isNavigationControllerModel = true;
    }
}

-(void) doneItemPressed:(id) sender
{
    if (doneDelegate) {
        [doneDelegate performSelector:doneSel withObject:weibo withObject:false];
    }
    [self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.weiboAuthview setFrame:self.view.bounds];
    
    [authview setScalesPageToFit:true];    
    [authview setContentMode:UIViewContentModeScaleToFill];
    [weibo auth: self];
}

-(UIWebView*) weiboAuthview 
{
    return authview;
}

-(void) authCallbackCurrentRequest:(NSURLRequest*)request 
{
    
}

-(void) authCallback 
{
    //[self.navigationController popViewControllerAnimated:YES];
    if (g_setFollowWhenAuth) {
        [weibo follow:self idx:YUIKE_WEIBO_ID_SINA];
    } else {
        [weibo getUserInfo:self];
    }
}

-(void) followCallback:(WeiboBase*)weibox idx:(long long)idx result:(BOOL)result {
    [weibo getUserInfo:self];
}

-(void) getUserInfoError: (WeiboBase*)weibo_ {
    // 失败为 小概率 事件
    [weibo signOutx];

    if (isNavigationControllerModel) { // 堆栈底的 controller
        [self.navigationController popViewControllerAnimated:true];
    } else {
        [self.parentViewController dismissModalViewControllerAnimated:YES];
    }
}
-(void) getUserInfoCallback:(WeiboBase*)weibo_ nick:(NSString*)name domain:(NSString*)url user:(WeiboUserNode*)user {
    [weibo setMyUserName: name];
    [weibo setMyDomainUrl: url];
    if (doneDelegate) {
        [doneDelegate performSelector:doneSel withObject:weibo withObject:(id)true];
    }

    if (isNavigationControllerModel) { // 堆栈底的 controller
        [self.navigationController popViewControllerAnimated:true];
    } else {
        [self.parentViewController dismissModalViewControllerAnimated:YES];
    }
}

-(void) setDoneDelegate:(id)delegate sel:(SEL)sel
{
    doneDelegate = delegate;
    doneSel = sel;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    authview.delegate = nil;
	[authview loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @""]]];
	[authview release];
    authview = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return TRUE;
}

@end
